package com.likuicat.picture_ddd.interfaces.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.likuicat.picture_ddd.application.service.PictureApplicationService;
import com.likuicat.picture_ddd.application.service.UserApplicationService;
import com.likuicat.picture_ddd.domain.picture.entity.Picture;
import com.likuicat.picture_ddd.domain.picture.valueobject.PictureReviewStatusEnum;
import com.likuicat.picture_ddd.domain.user.constant.UserConstant;
import com.likuicat.picture_ddd.domain.user.entity.User;
import com.likuicat.picture_ddd.infrastructure.annotation.AuthCheck;
import com.likuicat.picture_ddd.infrastructure.api.aliyunai.AliYunAiApi;
import com.likuicat.picture_ddd.infrastructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.likuicat.picture_ddd.infrastructure.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.likuicat.picture_ddd.infrastructure.api.imagesearch.ImageSearchApiFacade;
import com.likuicat.picture_ddd.infrastructure.api.imagesearch.model.ImageSearchResult;
import com.likuicat.picture_ddd.infrastructure.common.BaseResponse;
import com.likuicat.picture_ddd.infrastructure.common.DeleteRequest;
import com.likuicat.picture_ddd.infrastructure.common.ResultUtils;
import com.likuicat.picture_ddd.infrastructure.exception.BusinessException;
import com.likuicat.picture_ddd.infrastructure.exception.ErrorCode;
import com.likuicat.picture_ddd.infrastructure.exception.ThrowUtils;
import com.likuicat.picture_ddd.interfaces.assembler.PictureAssembler;
import com.likuicat.picture_ddd.interfaces.dto.picture.*;
import com.likuicat.picture_ddd.interfaces.vo.picture.PictureTagCategory;
import com.likuicat.picture_ddd.interfaces.vo.picture.PictureVO;
import com.likuicat.picture_ddd.shared.auth.SpaceUserAuthManager;
import com.likuicat.picture_ddd.shared.cache.MultiCacheTemplate;
import com.likuicat.picture_ddd.shared.auth.StpKit;
import com.likuicat.picture_ddd.shared.auth.annotation.SaSpaceCheckPermission;
import com.likuicat.picture_ddd.shared.auth.model.SpaceUserPermissionConstant;
import com.likuicat.picture_ddd.domain.space.entity.Space;
import com.likuicat.picture_ddd.application.service.SpaceApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Api(tags = "图片管理接口")
@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private PictureApplicationService pictureApplicationService;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private MultiCacheTemplate multiCacheTemplate;

    @Resource
    private SpaceApplicationService spaceApplicationService;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @ApiOperation("上传图片")
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile file,
            PictureUploadRequest pictureUpdateRequest,
            HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        PictureVO pictureVO = pictureApplicationService.uploadPicture(file, pictureUpdateRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    @ApiOperation("通过url上传图片")
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUpdateRequest,
            HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        String fileUrl = pictureUpdateRequest.getFileUrl();
        PictureVO pictureVO = pictureApplicationService.uploadPicture(fileUrl, pictureUpdateRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    @ApiOperation("批量上传图片(仅管理员)")
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUpdateRequest,
            HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        int uploadCount = pictureApplicationService.uploadPictureByBatch(pictureUpdateRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    @ApiOperation("删除图片")
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.NOT_FOUND_ERROR);
        Long id = deleteRequest.getId();
        ThrowUtils.throwIf(id <= 0,ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.deletePicture(id, loginUser);
        return ResultUtils.success(true);
    }

    @ApiOperation("根据id获取图片(仅管理员)")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id,HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.NOT_FOUND_ERROR);
        Picture picture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(picture);
    }

    @ApiOperation("根据id获取图片(封装类)")
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id,HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.NOT_FOUND_ERROR);
        Picture picture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        //空间权限校验
        Long spaceId = picture.getSpaceId();
        Space space = null;
        if(spaceId != null){
            //编程式鉴权
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceApplicationService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 获取权限列表
        User loginUser = userApplicationService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureApplicationService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        return ResultUtils.success(pictureVO);
    }

    @ApiOperation("分页获取图片列表(仅管理员)")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest){
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        Page<Picture> page = pictureApplicationService.page(new Page<>(current, pageSize),
                pictureApplicationService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(page);
    }

    @ApiOperation("分页获取图片列表(封装类)")
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                           HttpServletRequest request){
        // 1.校验
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20,ErrorCode.PARAMS_ERROR);
        Long spaceId = pictureQueryRequest.getSpaceId();
        if(spaceId == null){
            //普通用户只能查看过审后的图片数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            //只允许查看公共的图片
            pictureQueryRequest.setNullSpaceId(true);
        }else{
            //私人空间，校验权限
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
        }
        //查询数据库
        QueryWrapper<Picture> queryWrapper = pictureApplicationService.getQueryWrapper(pictureQueryRequest);
        Page<Picture> page = pictureApplicationService.page(new Page<>(current, pageSize),queryWrapper);
        Page<PictureVO> pictureVOPage = pictureApplicationService.getPictureVOPage(page, request);
        return ResultUtils.success(pictureVOPage);
    }

    @Deprecated
    @ApiOperation("分页获取图片列表(封装类，有缓存)")
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request){
        // 1.校验
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20,ErrorCode.PARAMS_ERROR);
        //使用多级缓存
        Page<PictureVO> pictureVOPage = multiCacheTemplate.multiLevelCache(pictureQueryRequest, new TypeReference<Page<PictureVO>>() {}, queryRequest -> {
            Long spaceId = queryRequest.getSpaceId();
            if(spaceId == null){
                //普通用户只能查看过审后的图片数据
                queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
                //只允许查看公共的图片
                queryRequest.setNullSpaceId(true);
            }else{
                //私人空间，校验权限
                User loginUser = userApplicationService.getLoginUser(request);
                Space space = spaceApplicationService.getById(spaceId);
                ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
                if(!space.getUserId().equals(loginUser.getId())){
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无空间权限");
                }
            }
            //查询数据库
            QueryWrapper<Picture> queryWrapper = pictureApplicationService.getQueryWrapper(queryRequest);
            Page<Picture> page = pictureApplicationService.page(new Page<>(current, pageSize),queryWrapper);
            return pictureApplicationService.getPictureVOPage(page, request);
        });
        return ResultUtils.success(pictureVOPage);
    }

    @ApiOperation("更新图片(仅管理员)")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                               HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0, ErrorCode.NOT_FOUND_ERROR);
        Picture picture = PictureAssembler.toPictureEntity(pictureUpdateRequest);
        //注意tags类型转化
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        //校验图片是否合规
        pictureApplicationService.validPicture(picture);
        //判断是否存在
        Long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR,"图片不存在");
        //补充审核参数
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.fillReviewParams(picture,loginUser);
        //更新数据库
        boolean result = pictureApplicationService.updateById(picture);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"更新图片失败");
        return ResultUtils.success(true);
    }

    @ApiOperation("编辑图片(用户使用)")
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest,HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditRequest == null,ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        Picture pictureEntity = PictureAssembler.toPictureEntity(pictureEditRequest);
        pictureApplicationService.editPicture(pictureEntity, loginUser);
        return ResultUtils.success(true);
    }

    @ApiOperation("标签")
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        //在项目前期规模不大的时候，我们没必要将标签和分类单独用数据表来维护了，直接在PictureController中写一个接口，返回预设的固定数据即可：
        //todo 随着系统规模和数据不断扩大，可以再改为使用配置中心或数据库动态管理这些数据，或者通过定时任务计算出热门的图片分类和标签。
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    @ApiOperation("图片审核")
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null,ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    @ApiOperation("以图搜图")
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureApplicationService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        return ResultUtils.success(resultList);
    }

    @ApiOperation("颜色搜索(私人空间)")
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest
                ,HttpServletRequest request){
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        String picColor = searchPictureByColorRequest.getPicColor();
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        List<PictureVO> pictureVOList = pictureApplicationService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(pictureVOList);
    }

    @ApiOperation("批量编辑图片")
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> pictureEditByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest,HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.pictureEditByBatch(pictureEditByBatchRequest,loginUser);
        return ResultUtils.success(true);
    }

    @ApiOperation("创建ai扩图任务")
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
                                                              HttpServletRequest request) {
        if(createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userApplicationService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureApplicationService.creatPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    @ApiOperation("查询ai扩图任务")
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId){
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse outPaintingTask = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(outPaintingTask);
    }

}
